<template>
  <div class="login">
      <el-form 
      ref="loginFormRef" 
      label-width="120px" 
      class="loginForm" 
      status-icon
      :model="loginForm"
      :rules="rules"
      >
          <el-form-item label="用户名" prop="username" label-width="120px">
              <el-input v-model="loginForm.username"/>
          </el-form-item>
          <el-form-item label="密码" prop="password" label-width="120px">
              <el-input v-model="loginForm.password" autocomplete="off" type="password"/>
          </el-form-item>
          <el-form-item>
              <el-button type="primary" @click="login(loginFormRef)">
                  登录
              </el-button>
              <el-button @click="resetForm">重置</el-button>
          </el-form-item>
      </el-form>
  </div>
</template>

<script setup lang="ts">
//自定义类型引入
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { ref,reactive } from 'vue';
import { useRouter } from 'vue-router';
import { userlogin } from '../request/api';
import { useStore } from 'vuex';
let store = useStore();
//定义路由控制器
let router = useRouter();
//定义form表单节点
let loginFormRef = ref<FormInstance>()
let loginForm = reactive({
  username:'',
  password:''
});
let rules = reactive<FormRules>({
  username:[
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 11, message: '长度 3 到 11 之间', trigger: 'blur' },
  ],
  password:[
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 3, max: 16, message: '长度 3 到 16 之间', trigger: 'blur' },
  ]
});
let login = (formEl:FormInstance|undefined) => {
  if(formEl){
      formEl.validate((val)=>{
          console.log(val,'判断的状态')
          if(val){
              //调用登录接口
              userlogin(loginForm)
              .then((res:any)=>{
                if(res.code==200){
                  ElMessage.success('登录成功')
                  //注意： 先存储后跳转
                  store.dispatch('changeUserAction',res.list)
                  router.push('/index')
                }else{
                  ElMessage.error(res.data.msg)
                }
              })
          }
      })
  }
};
let resetForm=()=>{
  loginFormRef.value?.resetFields()
}
</script>

<style scoped>
.login {
  width: 100vw;
  height: 100vh;
}

.loginForm {
  position: absolute;
  width: 400px;
  height: 350px;
  left: 50%;
  top: 50%;
  margin: -150px 0 0 -250px;
}
</style>